package com.yks.pls.pdf;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * zengzheng
 */
public class GoogleTranslateUtil {




    public  static List<String> translate(List<String> textList, String from, String to, String model) {

        String baseUrl = "https://translation.googleapis.com/language/translate/v2?";

        String key = "AIzaSyC78yesiFy7JAZJplPEMof1sK-FEBk5MLg";

        if (isNullOrEmpty(baseUrl)) {
            baseUrl = "https://translation.googleapis.com/language/translate/v2?";
        }

        if(isNullOrEmpty(key)) {
            key = "AIzaSyC78yesiFy7JAZJplPEMof1sK-FEBk5MLg";
        }
        StringBuilder result = new StringBuilder();
        StringBuilder translateUrl = new StringBuilder();
        try {
            translateUrl.append(baseUrl).append("key=").append(key);
            if(!isNullOrEmpty(to)){
                translateUrl.append("&target=").append(to);
            }
            if(!isNullOrEmpty(from)){
                translateUrl.append("&source=").append(from);
            }
            if(!isNullOrEmpty(model)){
                translateUrl.append("&model=").append(model);
            }
            for (String string : textList) {
                if(isNullOrEmpty(string)){
                    string = "";
                }
                translateUrl.append("&q=").append(URLEncoder.encode(string, "UTF-8"));
            }
            URL url = new URL(translateUrl.toString());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            InputStream stream;
            if (conn.getResponseCode() == 200) {
                //success
                stream = conn.getInputStream();
            } else{
                stream = conn.getErrorStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            return Collections.singletonList(result.toString());
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    private static boolean isNullOrEmpty(String baseUrl) {
        if(null == baseUrl){
            return true;
        }else if("".equals(baseUrl)){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        List<String> translte = translate(Arrays.asList("你好", "我是小明"), null, "fr", null);
        System.out.println(translte);
    }
}
